<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>C++中const变量的修改与赋值 | Tom's develop Blog</title><meta name="keywords" content="C++,const"><meta name="author" content="Tom"><meta name="copyright" content="Tom"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><meta name="description" content="C++中const变量的修改与赋值">
<meta property="og:type" content="article">
<meta property="og:title" content="C++中const变量的修改与赋值">
<meta property="og:url" content="https://tomsworkspace.github.io/2021/02/25/C++%E4%B8%ADconst%E5%8F%98%E9%87%8F%E7%9A%84%E4%BF%AE%E6%94%B9%E4%B8%8E%E8%B5%8B%E5%80%BC/index.html">
<meta property="og:site_name" content="Tom&#39;s develop Blog">
<meta property="og:description" content="C++中const变量的修改与赋值">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/TOMsworkspace/TOMsworkspace.github.io/2021/02/25/C++中const变量的修改与赋值/figure1.jpg">
<meta property="article:published_time" content="2021-02-25T12:26:16.000Z">
<meta property="article:modified_time" content="2021-02-27T12:13:02.506Z">
<meta property="article:author" content="Tom">
<meta property="article:tag" content="C++">
<meta property="article:tag" content="Const">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.jsdelivr.net/gh/TOMsworkspace/TOMsworkspace.github.io/2021/02/25/C++中const变量的修改与赋值/figure1.jpg"><link rel="shortcut icon" href="https://cdn.jsdelivr.net/gh/TOMsworkspace/BlogHelper@1.0/avatar.png"><link rel="canonical" href="https://tomsworkspace.github.io/2021/02/25/C++%E4%B8%ADconst%E5%8F%98%E9%87%8F%E7%9A%84%E4%BF%AE%E6%94%B9%E4%B8%8E%E8%B5%8B%E5%80%BC/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="preconnect" href="//zz.bdstatic.com"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css"><script>var GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: Tom","link":"链接: ","source":"来源: Tom's develop Blog","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  ClickShowText: {"text":"富强,民主,文明,和谐,自由,平等,公正,法治,爱国,敬业,诚信,友善","fontSize":"15px"},
  lightbox: 'mediumZoom',
  Snackbar: undefined,
  justifiedGallery: {
    js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
    css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isanchor: false
};

var saveToLocal = {
  set: function setWithExpiry(key, value, ttl) {
    const now = new Date()
    const expiryDay = ttl * 86400000
    const item = {
      value: value,
      expiry: now.getTime() + expiryDay,
    }
    localStorage.setItem(key, JSON.stringify(item))
  },

  get: function getWithExpiry(key) {
    const itemStr = localStorage.getItem(key)

    if (!itemStr) {
      return undefined
    }
    const item = JSON.parse(itemStr)
    const now = new Date()

    if (now.getTime() > item.expiry) {
      localStorage.removeItem(key)
      return undefined
    }
    return item.value
  }
}</script><script id="config_change">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-02-27 20:13:02'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(function () {  window.activateDarkMode = function () {
    document.documentElement.setAttribute('data-theme', 'dark')
    if (document.querySelector('meta[name="theme-color"]') !== null) {
      document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
    }
  }
  window.activateLightMode = function () {
    document.documentElement.setAttribute('data-theme', 'light')
   if (document.querySelector('meta[name="theme-color"]') !== null) {
      document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
    }
  }
  const autoChangeMode = 'true'
  const t = saveToLocal.get('theme')
  if (autoChangeMode === '1') {
    const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
    const isLightMode = window.matchMedia('(prefers-color-scheme: light)').matches
    const isNotSpecified = window.matchMedia('(prefers-color-scheme: no-preference)').matches
    const hasNoSupport = !isDarkMode && !isLightMode && !isNotSpecified
    if (t === undefined) {
      if (isLightMode) activateLightMode()
      else if (isDarkMode) activateDarkMode()
      else if (isNotSpecified || hasNoSupport) {
        const now = new Date()
        const hour = now.getHours()
        const isNight = hour <= 6 || hour >= 18
        isNight ? activateDarkMode() : activateLightMode()
      }
      window.matchMedia('(prefers-color-scheme: dark)').addListener(function (e) {
        if (saveToLocal.get('theme') === undefined) {
          e.matches ? activateDarkMode() : activateLightMode()
        }
      })
    } else if (t === 'light') activateLightMode()
    else activateDarkMode()
  } else if (autoChangeMode === '2') {
    const now = new Date()
    const hour = now.getHours()
    const isNight = hour <= 6 || hour >= 18
    if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
    else if (t === 'light') activateLightMode()
    else activateDarkMode()
  } else {
    if (t === 'dark') activateDarkMode()
    else if (t === 'light') activateLightMode()
  }})()</script><meta name="generator" content="Hexo 5.2.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" data-lazy-src="https://cdn.jsdelivr.net/gh/TOMsworkspace/BlogHelper@1.0/avator.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">38</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">73</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">12</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> Home</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> Archives</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> Tags</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> Categories</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> Link</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> About</span></a></div></div></div></div><div id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url(https://cdn.jsdelivr.net/gh/TOMsworkspace/TOMsworkspace.github.io/2021/02/25/C++中const变量的修改与赋值/figure1.jpg)"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Tom's develop Blog</a></span><span id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> Home</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> Archives</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> Tags</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> Categories</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> Link</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> About</span></a></div></div><span class="close" id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></span></span></nav><div id="post-info"><h1 class="post-title">C++中const变量的修改与赋值</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-02-25T12:26:16.000Z" title="发表于 2021-02-25 20:26:16">2021-02-25</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-02-27T12:13:02.506Z" title="更新于 2021-02-27 20:13:02">2021-02-27</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/C-C/">C/C++</a></span></div><div class="meta-secondline"> <span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.4k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>8分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span><span class="post-meta-separator">|</span><span class="post-meta-commentcount"><i class="far fa-comments fa-fw post-meta-icon"></i><span class="post-meta-label">评论数:</span><a href="/2021/02/25/C++%E4%B8%ADconst%E5%8F%98%E9%87%8F%E7%9A%84%E4%BF%AE%E6%94%B9%E4%B8%8E%E8%B5%8B%E5%80%BC/#post-comment"><span class="gitalk-comment-count comment-count"></span></a></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><p>&emsp;出于避免对数据的无意修改的需求，C及C++语言引入了const关键字。与C语言中的const相比，C++中的const具有更丰富的用法。C++中的const除了可用于修饰变量，指针，函数及函数参数，还可用于修饰类对象，类成员，类成员函数等。由于其丰富的用途，往往容易对其产生误解，尤其是与指针用法结合在一起时。下面以一些实例来说明这个问题。</p>
<h2 id="一、const修饰变量"><a href="#一、const修饰变量" class="headerlink" title="一、const修饰变量"></a>一、const修饰变量</h2><h3 id="1、含义"><a href="#1、含义" class="headerlink" title="1、含义"></a>1、含义</h3><p>&emsp;当使用const修饰普通变量时。如</p>
<figure class="highlight c++"><table><tr><td class="code"><pre><span class="line"><span class="keyword">int</span> <span class="keyword">const</span> age = <span class="number">39</span>;</span><br><span class="line"><span class="comment">//或</span></span><br><span class="line"><span class="keyword">const</span> <span class="keyword">int</span> age = <span class="number">39</span>;</span><br></pre></td></tr></table></figure>
<p>&emsp;表示const关键字修饰的这个变量是一个常量，不能对其值进行修改。但实际上这句话不是绝对的。根据C++标准，对于修改const变量，属于未定义行为（指行为不可预测的计算机代码），这样一来这个行为的结果取决于各种编译器的具体实现（即不同编译器可能表现不同）。</p>
<h3 id="2、修改const变量"><a href="#2、修改const变量" class="headerlink" title="2、修改const变量"></a>2、修改const变量</h3><p>&emsp;下面来说一下如何修改const修饰的变量。可以使用直接赋值和使用指针来修改其值。如：</p>
<figure class="highlight c++"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="keyword">int</span> age = <span class="number">39</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">//1.直接赋值</span></span><br><span class="line">age = <span class="number">40</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">//2.使用指针修改</span></span><br><span class="line"><span class="keyword">int</span> * p = (<span class="keyword">int</span> *)&amp;age;</span><br><span class="line">*p = <span class="number">40</span>;</span><br><span class="line"></span><br><span class="line"><span class="built_in">cout</span> &lt;&lt; <span class="string">&quot;age=&quot;</span> &lt;&lt; age &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line"><span class="built_in">cout</span> &lt;&lt; <span class="string">&quot;*p=&quot;</span> &lt;&lt; *p &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line"><span class="built_in">cout</span> &lt;&lt; <span class="string">&quot;&amp;age=&quot;</span> &lt;&lt; &amp;age &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line"><span class="built_in">cout</span> &lt;&lt; <span class="string">&quot;p=&quot;</span> &lt;&lt; (<span class="keyword">void</span>*)p &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line"><span class="built_in">cout</span> &lt;&lt; <span class="string">&quot;&amp;p=&quot;</span> &lt;&lt; &amp;p &lt;&lt; <span class="built_in">endl</span>;</span><br></pre></td></tr></table></figure>
<p>&emsp;这段代码对于age变量是全局变量还是局部变量结果并不一样。</p>
<h4 id="（1）修改局部变量"><a href="#（1）修改局部变量" class="headerlink" title="（1）修改局部变量"></a>（1）修改局部变量</h4><p>&emsp;程序能正常运行，且常量被修改了，但是有一个问题：输出age的值和*p的值并不相同，age的值还是39，而*p的值是40。而且p确实指向age所在的地址空间。</p>
<p>&emsp;这是什么原因呢？难道一个地址空间可以存储不同的俩个值？当然不能。这就是C++中的<strong>常量折叠</strong>：const变量（即常量）值放在编译器的符号表中，计算时编译器直接从表中取值，省去了访问内存的时间，这是编译器进行的优化。age是const变量，编译器对age在预处理的时候就进行了替换。编译器只对const变量的值读取一次。所以打印的是39。age实际存储的值被指针p所改变。但是为什么能改变呢，从其存储地址可以看出来，其存储在堆栈中。</p>
<h4 id="（2）修改全局变量"><a href="#（2）修改全局变量" class="headerlink" title="（2）修改全局变量"></a>（2）修改全局变量</h4><p>&emsp;程序编译通过，但运行时错误。编译器提示age存储的空间不可写，也就是没有写权限，不能修改其值。<br>&emsp;原因是age是全局变量，全局变量存储在全局空间，且只有可读属性，无法修改其值。</p>
<h4 id="（3）volatile关键字"><a href="#（3）volatile关键字" class="headerlink" title="（3）volatile关键字"></a>（3）volatile关键字</h4><p>&emsp;由于编译器对const修饰的局部变量进行了优化，使得对于const变量值的读取实际没有进入内存。而在此基础上加上volatile关键字，即告诉编译器该变量属于易变的，不要对此句进行优化，每次计算时要去内存中读取该变量的值,进而避免出现<strong>常量折叠</strong>的问题。可以这样做：</p>
<figure class="highlight c++"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="keyword">volatile</span> <span class="keyword">int</span> age = <span class="number">39</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">//1.直接赋值</span></span><br><span class="line">age = <span class="number">40</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">//2.使用指针修改</span></span><br><span class="line"><span class="keyword">int</span> * p = (<span class="keyword">int</span> *)&amp;age;</span><br><span class="line">*p = <span class="number">40</span>;</span><br><span class="line"></span><br><span class="line"><span class="built_in">cout</span> &lt;&lt; <span class="string">&quot;age=&quot;</span> &lt;&lt; age &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line"><span class="built_in">cout</span> &lt;&lt; <span class="string">&quot;*p=&quot;</span> &lt;&lt; *p &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line"><span class="built_in">cout</span> &lt;&lt; <span class="string">&quot;&amp;age=&quot;</span> &lt;&lt; &amp;age &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line"><span class="built_in">cout</span> &lt;&lt; <span class="string">&quot;p=&quot;</span> &lt;&lt; (<span class="keyword">void</span>*)p &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line"><span class="built_in">cout</span> &lt;&lt; <span class="string">&quot;&amp;p=&quot;</span> &lt;&lt; &amp;p &lt;&lt; <span class="built_in">endl</span>;</span><br></pre></td></tr></table></figure>

<p>&emsp;这里也有个问题：每种编译器对volatile关键字的支持效果并不一致，有的编译器就直接“不理会”，如VC++6.0编译器[1]，使得依然无法避免常量折叠的问题。</p>
<h4 id="（4）强制类型转换"><a href="#（4）强制类型转换" class="headerlink" title="（4）强制类型转换"></a>（4）强制类型转换</h4><p>&emsp;const修饰的变量在C++中被看作是常量，无法修改。但是存在这样的场景：<strong>有时候我们需要一个一个值，它在大多数时候是常量，但是在又是又是可以更改的。</strong>这时候就需要使用指针来对const变量进行修改。但是在上面的例子中使用到了强制类型转换：</p>
<figure class="highlight c++"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="keyword">volatile</span> <span class="keyword">int</span> age = <span class="number">39</span>;</span><br><span class="line"><span class="comment">//使用指针修改</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//不使用强制类型转换</span></span><br><span class="line"><span class="keyword">int</span> * p = &amp;age;  </span><br><span class="line"></span><br><span class="line"><span class="comment">//强制类型转换</span></span><br><span class="line"><span class="keyword">int</span> * p = (<span class="keyword">int</span> *)&amp;age;  </span><br><span class="line"><span class="comment">//或</span></span><br><span class="line"><span class="keyword">int</span> * p = <span class="keyword">const_cast</span>&lt;<span class="keyword">int</span> *&gt;(&amp;age); </span><br><span class="line"></span><br><span class="line">*p = <span class="number">40</span>;</span><br></pre></td></tr></table></figure>
<p>&emsp;在这里如果不使用强制类型转换，等于是将一个const int * 类型赋值给一个int * 类型，无法编译通过。必须使用强制类型转换。</p>
<h2 id="二、const-修饰指针"><a href="#二、const-修饰指针" class="headerlink" title="二、const 修饰指针"></a>二、const 修饰指针</h2><p>&emsp;当使用const修饰指针变量时，情况更加复杂起来了。const可以放置在不同的地方，因此具有不同的含义。请看下面一个例子：</p>
<figure class="highlight c++"><table><tr><td class="code"><pre><span class="line"><span class="keyword">int</span> age = <span class="number">39</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="keyword">int</span> * p = &amp;age;</span><br><span class="line"></span><br><span class="line"><span class="keyword">int</span> <span class="keyword">const</span> * p = &amp;age;</span><br><span class="line"></span><br><span class="line"><span class="keyword">int</span> * <span class="keyword">const</span> p = &amp;age;</span><br><span class="line"></span><br><span class="line"><span class="keyword">int</span> * p <span class="keyword">const</span> = &amp;age;</span><br></pre></td></tr></table></figure>
<p>&emsp;在这个例子中，一二两种情况是一个意思，表示p是一个指向const的指针；第三种用法表示p是一个常量指针；第四种情况不符合语法。</p>
<h3 id="1、指向常量（const）的指针和常量-const-指针"><a href="#1、指向常量（const）的指针和常量-const-指针" class="headerlink" title="1、指向常量（const）的指针和常量(const)指针"></a>1、指向常量（const）的指针和常量(const)指针</h3><p>&emsp;故名思意：<strong>指向常量的指针</strong>表示const修饰的指针是指向常量的，不能用这个指针来修改它指向的值，但是可以让该指针指向其他地址。这里就有个问题：age明明是一个变量，为什么可以赋值给一个指向常量(const)的指针？原因是这里发生了隐式的类型转换，&amp;age是一个int * 类型，而p是一个const int * 类型，从int *到const int *是从大范围到小范围，C++进行了隐式的转换，所以能够赋值成功。前一节的从const int * 到int * 是从小范围到一个大范围，无法进行隐式类型转换，所以必须进行强制（显式）类型转换才能赋值成功就是这个原因了。</p>
<p>&emsp;<strong>常量指针</strong>表示指针的值是常量，也就是不能修改指针指向的位置，但是可以修改该指针指向的变量的值。</p>
<p>&emsp;那一个指针能不能既是指向常量的指针又是常量指针呢？这是可以的。例如：</p>
<figure class="highlight c++"><table><tr><td class="code"><pre><span class="line"><span class="keyword">int</span> age = <span class="number">39</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="keyword">int</span> * <span class="keyword">const</span> p = &amp;age;</span><br></pre></td></tr></table></figure>
<p>&emsp;此时的p表示既不能修改它指向的位置的变量的值，又不能使p指向其他位置的变量。</p>
<h3 id="2、修改指向常量的指针"><a href="#2、修改指向常量的指针" class="headerlink" title="2、修改指向常量的指针"></a>2、修改指向常量的指针</h3><p>&emsp;使用如下的例子来修改指向常量的指针：</p>
<figure class="highlight c++"><table><tr><td class="code"><pre><span class="line"><span class="keyword">int</span> age = <span class="number">39</span>;</span><br><span class="line"><span class="keyword">int</span> year = <span class="number">2021</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="keyword">int</span> * p = &amp;age;</span><br><span class="line"></span><br><span class="line"><span class="comment">//修改p指向变量的值,编译错误</span></span><br><span class="line">*p = <span class="number">40</span>;</span><br><span class="line"><span class="comment">//修改指针p的值，可以修改</span></span><br><span class="line">p = &amp;year;</span><br></pre></td></tr></table></figure>
<p>&emsp;运行发现确实无法修改p指向的值，编译错误；但是可以修改指针P的值，让它指向另外的变量year。</p>
<h3 id="3、修改常量指针"><a href="#3、修改常量指针" class="headerlink" title="3、修改常量指针"></a>3、修改常量指针</h3><p>&emsp;使用如下的例子来修改常量指针：</p>
<figure class="highlight c++"><table><tr><td class="code"><pre><span class="line"><span class="keyword">int</span> age = <span class="number">39</span>;</span><br><span class="line"><span class="keyword">int</span> year = <span class="number">2021</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">int</span> * <span class="keyword">const</span> p = &amp;age;</span><br><span class="line"></span><br><span class="line"><span class="comment">//修改p指向变量的值,可以修改</span></span><br><span class="line">*p = <span class="number">40</span>;</span><br><span class="line"><span class="comment">//修改指针p的值，编译错误</span></span><br><span class="line">p = &amp;year;</span><br></pre></td></tr></table></figure>
<p>&emsp;运行发现可以修改p指向的值；但是不能修改指针P的值，让它指向另外的变量year。</p>
<p>&emsp;对于既是既是指向常量的指针又是常量指针，则既无法修改指向的值，又无法修改指针的值，让它指向另外的变量。</p>
<figure class="highlight c++"><table><tr><td class="code"><pre><span class="line"><span class="keyword">int</span> age = <span class="number">39</span>;</span><br><span class="line"><span class="keyword">int</span> year = <span class="number">2021</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="keyword">int</span> * <span class="keyword">const</span> p = &amp;age;</span><br><span class="line"></span><br><span class="line"><span class="comment">//修改p指向变量的值,编译错误</span></span><br><span class="line">*p = <span class="number">40</span>;</span><br><span class="line"><span class="comment">//修改指针p的值，编译错误</span></span><br><span class="line">p = &amp;year;</span><br></pre></td></tr></table></figure>
<h2 id="三、使用const的好处"><a href="#三、使用const的好处" class="headerlink" title="三、使用const的好处"></a>三、使用const的好处</h2><h3 id="1、可以定义const常量"><a href="#1、可以定义const常量" class="headerlink" title="1、可以定义const常量"></a>1、可以定义const常量</h3><p>&emsp;这样可以避免由于无意间修改数据而导致的编程错误。</p>
<h3 id="2、便于进行类型检查"><a href="#2、便于进行类型检查" class="headerlink" title="2、便于进行类型检查"></a>2、便于进行类型检查</h3><p>&emsp;const常量有数据类型，而宏常量没有数据类型。编译器可以对前者进行类型安全检查，而对后者只进行字符替换，没有类型安全检查，并且在字符替换时可能会产生意料不到的错误。</p>
<h3 id="3、为函数重载提供了一个参考"><a href="#3、为函数重载提供了一个参考" class="headerlink" title="3、为函数重载提供了一个参考"></a>3、为函数重载提供了一个参考</h3><p>&emsp;const修饰的函数可以看作是对同名函数的重载。</p>
<h3 id="4、可以节省空间，避免不必要的内存分配"><a href="#4、可以节省空间，避免不必要的内存分配" class="headerlink" title="4、可以节省空间，避免不必要的内存分配"></a>4、可以节省空间，避免不必要的内存分配</h3><p>&emsp;const定义常量从汇编的角度来看，只是给出了对应的内存地址，而不是象宏一样给出的是立即数，所以，const定义的常量在程序运行过程中只有一份拷贝，而宏定义的常量在内存中有若干个拷贝。</p>
<h3 id="5、提高了效率"><a href="#5、提高了效率" class="headerlink" title="5、提高了效率"></a>5、提高了效率</h3><p>&emsp;编译器通常不为普通const常量分配存储空间，而是将它们保存在符号表中，这使得它成为一个编译期的常量，没有了存储与读内存的操作，使得它的效率也很高。</p>
<p>[1]<a target="_blank" rel="noopener" href="https://blog.csdn.net/zz460833359/article/details/48917217">https://blog.csdn.net/zz460833359/article/details/48917217</a><br>[2]<a target="_blank" rel="noopener" href="https://blog.csdn.net/niusi1288/article/details/90710176?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_title-3&amp;spm=1001.2101.3001.4242">https://blog.csdn.net/niusi1288/article/details/90710176?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_title-3&amp;spm=1001.2101.3001.4242</a><br>[3]<a target="_blank" rel="noopener" href="https://blog.csdn.net/qq_30968657/article/details/53837022">https://blog.csdn.net/qq_30968657/article/details/53837022</a><br>[4]<a target="_blank" rel="noopener" href="https://blog.csdn.net/Eric_Jo/article/details/4138548?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.control&amp;dist_request_id=1ba4e5e7-1d6a-4d31-9b36-5fcc5bb702fa&amp;depth_1-utm_source=distribute.pc_relevant.none-task-blog-Blog">https://blog.csdn.net/Eric_Jo/article/details/4138548?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.control&amp;dist_request_id=1ba4e5e7-1d6a-4d31-9b36-5fcc5bb702fa&amp;depth_1-utm_source=distribute.pc_relevant.none-task-blog-Blog</a> CommendFromMachineLearnPai2-1.control<br>[5]<a target="_blank" rel="noopener" href="https://blog.csdn.net/Eric_Jo/article/details/4138548?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.control&amp;dist_request_id=1ba4e5e7-1d6a-4d31-9b36-5fcc5bb702fa&amp;depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.control">https://blog.csdn.net/Eric_Jo/article/details/4138548?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.control&amp;dist_request_id=1ba4e5e7-1d6a-4d31-9b36-5fcc5bb702fa&amp;depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.control</a></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">Tom</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://tomsworkspace.github.io/2021/02/25/C++%E4%B8%ADconst%E5%8F%98%E9%87%8F%E7%9A%84%E4%BF%AE%E6%94%B9%E4%B8%8E%E8%B5%8B%E5%80%BC/">https://tomsworkspace.github.io/2021/02/25/C++%E4%B8%ADconst%E5%8F%98%E9%87%8F%E7%9A%84%E4%BF%AE%E6%94%B9%E4%B8%8E%E8%B5%8B%E5%80%BC/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://TOMsworkspace.github.io" target="_blank">Tom's develop Blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/C/">C++</a><a class="post-meta__tags" href="/tags/Const/">Const</a></div><div class="post_share"><div class="social-share" data-image="https://cdn.jsdelivr.net/gh/TOMsworkspace/TOMsworkspace.github.io/2021/02/25/C++中const变量的修改与赋值/figure1.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏<div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://cdn.jsdelivr.net/gh/TOMsworkspace/BlogHelper@1.0/wp.jpg" target="_blank"><img class="post-qr-code-img" data-lazy-src="https://cdn.jsdelivr.net/gh/TOMsworkspace/BlogHelper@1.0/wp.jpg" alt="wechat"/></a><div class="post-qr-code-desc">wechat</div></li></ul></div></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2021/02/27/GCC%E8%87%AA%E5%B8%A6%E7%9A%84%E4%B8%80%E4%BA%9Bbuiltin%E5%86%85%E5%BB%BA%E5%87%BD%E6%95%B0/"><img class="prev-cover" data-lazy-src="https://cdn.jsdelivr.net/gh/TOMsworkspace/TOMsworkspace.github.io/2021/02/27/GCC自带的一些builtin内建函数/figure1.jpg" onerror="onerror=null;src='/img/404.jpg'"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">GCC自带的一些builtin内建函数</div></div></a></div><div class="next-post pull-right"><a href="/2020/11/25/C++%E5%85%B3%E9%94%AE%E5%AD%97%E4%B8%8E%E4%BF%9D%E7%95%99%E6%A0%87%E8%AF%86%E7%AC%A6/"><img class="next-cover" data-lazy-src="https://cdn.jsdelivr.net/gh/TOMsworkspace/TOMsworkspace.github.io/2020/11/25/C++关键字与保留标识符/figure1.jpg" onerror="onerror=null;src='/img/404.jpg'"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">C++关键字与保留标识符</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2021/03/05/C++参数传递方式及区别/" title="C++参数传递方式及区别"><img class="cover" data-lazy-src="https://cdn.jsdelivr.net/gh/TOMsworkspace/TOMsworkspace.github.io/2021/03/05/C++参数传递方式及区别/figure1.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-03-05</div><div class="title">C++参数传递方式及区别</div></div></a></div><div><a href="/2020/09/26/C++多继承时的虚函数表结构/" title="C++多继承时的虚函数表结构"><img class="cover" data-lazy-src="https://cdn.jsdelivr.net/gh/TOMsworkspace/TOMsworkspace.github.io/2020/09/26/C++多继承时的虚函数表结构/figure1.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-09-26</div><div class="title">C++多继承时的虚函数表结构</div></div></a></div><div><a href="/2020/11/23/C++语言标准/" title="C++语言标准"><img class="cover" data-lazy-src="https://cdn.jsdelivr.net/gh/TOMsworkspace/TOMsworkspace.github.io//2020/11/23/C++语言标准/figure1.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-11-23</div><div class="title">C++语言标准</div></div></a></div><div><a href="/2020/08/05/值得推荐的C与C++框架和库/" title="值得推荐的C与C++框架和库"><img class="cover" data-lazy-src="https://cdn.jsdelivr.net/gh/TOMsworkspace/BlogHelper/值得推荐的C与C++框架和库/figure1.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-08-05</div><div class="title">值得推荐的C与C++框架和库</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="gitalk-container"></div></div></div></div></div><div class="aside_content" id="aside_content"><div class="card-widget card-info"><div class="card-content"><div class="card-info-avatar is-center"><img class="avatar-img" data-lazy-src="https://cdn.jsdelivr.net/gh/TOMsworkspace/BlogHelper@1.0/avator.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">Tom</div><div class="author-info__description">keep curiously!</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">38</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">73</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">12</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/TOMsworkspace"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/TOMsworkspace" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:cqucscw@gmail.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div></div><div class="card-widget card-announcement"><div class="card-content"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="card-content"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%80%E3%80%81const%E4%BF%AE%E9%A5%B0%E5%8F%98%E9%87%8F"><span class="toc-number">1.</span> <span class="toc-text">一、const修饰变量</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%E3%80%81%E5%90%AB%E4%B9%89"><span class="toc-number">1.1.</span> <span class="toc-text">1、含义</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%E3%80%81%E4%BF%AE%E6%94%B9const%E5%8F%98%E9%87%8F"><span class="toc-number">1.2.</span> <span class="toc-text">2、修改const变量</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%EF%BC%881%EF%BC%89%E4%BF%AE%E6%94%B9%E5%B1%80%E9%83%A8%E5%8F%98%E9%87%8F"><span class="toc-number">1.2.1.</span> <span class="toc-text">（1）修改局部变量</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%EF%BC%882%EF%BC%89%E4%BF%AE%E6%94%B9%E5%85%A8%E5%B1%80%E5%8F%98%E9%87%8F"><span class="toc-number">1.2.2.</span> <span class="toc-text">（2）修改全局变量</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%EF%BC%883%EF%BC%89volatile%E5%85%B3%E9%94%AE%E5%AD%97"><span class="toc-number">1.2.3.</span> <span class="toc-text">（3）volatile关键字</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%EF%BC%884%EF%BC%89%E5%BC%BA%E5%88%B6%E7%B1%BB%E5%9E%8B%E8%BD%AC%E6%8D%A2"><span class="toc-number">1.2.4.</span> <span class="toc-text">（4）强制类型转换</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BA%8C%E3%80%81const-%E4%BF%AE%E9%A5%B0%E6%8C%87%E9%92%88"><span class="toc-number">2.</span> <span class="toc-text">二、const 修饰指针</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%E3%80%81%E6%8C%87%E5%90%91%E5%B8%B8%E9%87%8F%EF%BC%88const%EF%BC%89%E7%9A%84%E6%8C%87%E9%92%88%E5%92%8C%E5%B8%B8%E9%87%8F-const-%E6%8C%87%E9%92%88"><span class="toc-number">2.1.</span> <span class="toc-text">1、指向常量（const）的指针和常量(const)指针</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%E3%80%81%E4%BF%AE%E6%94%B9%E6%8C%87%E5%90%91%E5%B8%B8%E9%87%8F%E7%9A%84%E6%8C%87%E9%92%88"><span class="toc-number">2.2.</span> <span class="toc-text">2、修改指向常量的指针</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%E3%80%81%E4%BF%AE%E6%94%B9%E5%B8%B8%E9%87%8F%E6%8C%87%E9%92%88"><span class="toc-number">2.3.</span> <span class="toc-text">3、修改常量指针</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%89%E3%80%81%E4%BD%BF%E7%94%A8const%E7%9A%84%E5%A5%BD%E5%A4%84"><span class="toc-number">3.</span> <span class="toc-text">三、使用const的好处</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%E3%80%81%E5%8F%AF%E4%BB%A5%E5%AE%9A%E4%B9%89const%E5%B8%B8%E9%87%8F"><span class="toc-number">3.1.</span> <span class="toc-text">1、可以定义const常量</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%E3%80%81%E4%BE%BF%E4%BA%8E%E8%BF%9B%E8%A1%8C%E7%B1%BB%E5%9E%8B%E6%A3%80%E6%9F%A5"><span class="toc-number">3.2.</span> <span class="toc-text">2、便于进行类型检查</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%E3%80%81%E4%B8%BA%E5%87%BD%E6%95%B0%E9%87%8D%E8%BD%BD%E6%8F%90%E4%BE%9B%E4%BA%86%E4%B8%80%E4%B8%AA%E5%8F%82%E8%80%83"><span class="toc-number">3.3.</span> <span class="toc-text">3、为函数重载提供了一个参考</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4%E3%80%81%E5%8F%AF%E4%BB%A5%E8%8A%82%E7%9C%81%E7%A9%BA%E9%97%B4%EF%BC%8C%E9%81%BF%E5%85%8D%E4%B8%8D%E5%BF%85%E8%A6%81%E7%9A%84%E5%86%85%E5%AD%98%E5%88%86%E9%85%8D"><span class="toc-number">3.4.</span> <span class="toc-text">4、可以节省空间，避免不必要的内存分配</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5%E3%80%81%E6%8F%90%E9%AB%98%E4%BA%86%E6%95%88%E7%8E%87"><span class="toc-number">3.5.</span> <span class="toc-text">5、提高了效率</span></a></li></ol></li></ol></div></div></div><div class="card-widget card-recent-post"><div class="card-content"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2021/09/27/%E6%B5%81%E4%BD%93%E6%A8%A1%E6%8B%9F%E4%B8%8ESPH%E6%96%B9%E6%B3%95/" title="流体模拟与SPH方法"><img data-lazy-src="https://cdn.jsdelivr.net/gh/TOMsworkspace/TOMsworkspace.github.io/2021/09/27/流体模拟与SPH方法/figure1.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="流体模拟与SPH方法"/></a><div class="content"><a class="title" href="/2021/09/27/%E6%B5%81%E4%BD%93%E6%A8%A1%E6%8B%9F%E4%B8%8ESPH%E6%96%B9%E6%B3%95/" title="流体模拟与SPH方法">流体模拟与SPH方法</a><time datetime="2021-09-27T08:46:17.000Z" title="发表于 2021-09-27 16:46:17">2021-09-27</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/09/11/%E5%BC%B9%E6%80%A7%E6%9C%89%E9%99%90%E5%85%83%E6%96%B9%E6%B3%95/" title="弹性有限元方法"><img data-lazy-src="https://cdn.jsdelivr.net/gh/TOMsworkspace/TOMsworkspace.github.io/2021/09/11/弹性有限元方法/figure1.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="弹性有限元方法"/></a><div class="content"><a class="title" href="/2021/09/11/%E5%BC%B9%E6%80%A7%E6%9C%89%E9%99%90%E5%85%83%E6%96%B9%E6%B3%95/" title="弹性有限元方法">弹性有限元方法</a><time datetime="2021-09-11T09:05:34.000Z" title="发表于 2021-09-11 17:05:34">2021-09-11</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/08/09/%E5%BC%B9%E7%B0%A7%E8%B4%A8%E7%82%B9%E7%B3%BB%E7%BB%9F%E4%B8%8E%E6%97%B6%E9%97%B4%E7%A7%AF%E5%88%86/" title="弹簧质点系统与时间积分"><img data-lazy-src="https://cdn.jsdelivr.net/gh/TOMsworkspace/TOMsworkspace.github.io/2021/08/09/弹簧质点系统与时间积分/figure1.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="弹簧质点系统与时间积分"/></a><div class="content"><a class="title" href="/2021/08/09/%E5%BC%B9%E7%B0%A7%E8%B4%A8%E7%82%B9%E7%B3%BB%E7%BB%9F%E4%B8%8E%E6%97%B6%E9%97%B4%E7%A7%AF%E5%88%86/" title="弹簧质点系统与时间积分">弹簧质点系统与时间积分</a><time datetime="2021-08-09T13:39:12.000Z" title="发表于 2021-08-09 21:39:12">2021-08-09</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/08/08/OpenGL%E5%9D%90%E6%A0%87%E7%B3%BB%E7%BB%9F/" title="OpenGL坐标系统"><img data-lazy-src="https://cdn.jsdelivr.net/gh/TOMsworkspace/TOMsworkspace.github.io/2021/08/08/OpenGL坐标系统/figure1.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="OpenGL坐标系统"/></a><div class="content"><a class="title" href="/2021/08/08/OpenGL%E5%9D%90%E6%A0%87%E7%B3%BB%E7%BB%9F/" title="OpenGL坐标系统">OpenGL坐标系统</a><time datetime="2021-08-08T12:57:28.000Z" title="发表于 2021-08-08 20:57:28">2021-08-08</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/08/06/Doxygen%E8%87%AA%E5%8A%A8%E7%94%9F%E6%88%90%E6%96%87%E6%A1%A3/" title="Doxygen自动生成文档"><img data-lazy-src="https://cdn.jsdelivr.net/gh/TOMsworkspace/TOMsworkspace.github.io/2021/08/06/Doxygen自动生成文档/Doxygen.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Doxygen自动生成文档"/></a><div class="content"><a class="title" href="/2021/08/06/Doxygen%E8%87%AA%E5%8A%A8%E7%94%9F%E6%88%90%E6%96%87%E6%A1%A3/" title="Doxygen自动生成文档">Doxygen自动生成文档</a><time datetime="2021-08-06T13:24:50.000Z" title="发表于 2021-08-06 21:24:50">2021-08-06</time></div></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2019 - 2021 By Tom</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">Hi, welcome to my <a href="https://TOMsworkspace.github.io/">blog</a>!</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">简</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog"></i></button><button id="chat_btn" type="button" title="rightside.chat_btn"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/medium-zoom/dist/medium-zoom.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module" defer></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><div class="js-pjax"><script>if (!window.MathJax) {
  window.MathJax = {
    loader: {
      source: {
        '[tex]/amsCd': '[tex]/amscd'
      }
    },
    tex: {
      inlineMath: [ ['$','$'], ["\\(","\\)"]],
      tags: 'ams'
    },
    options: {
      renderActions: {
        findScript: [10, doc => {
          for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
            const display = !!node.type.match(/; *mode=display/)
            const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
            const text = document.createTextNode('')
            node.parentNode.replaceChild(text, node)
            math.start = {node: text, delim: '', n: 0}
            math.end = {node: text, delim: '', n: 0}
            doc.math.push(math)
          }
        }, ''],
        addClass: [200,() => {
          document.querySelectorAll('mjx-container:not([display=\'true\']').forEach( node => {
            const target = node.parentNode
            if (!target.classList.contains('has-jax')) {
              target.classList.add('mathjax-overflow')
            }
          })
        }, '', false]
      }
    }
  }
  
  const script = document.createElement('script')
  script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js'
  script.id = 'MathJax-script'
  script.async = true
  document.head.appendChild(script)
} else {
  MathJax.startup.document.state(0)
  MathJax.texReset()
  MathJax.typeset()
}</script><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/katex@latest/dist/katex.min.css"><script src="https://cdn.jsdelivr.net/npm/katex-copytex@latest/dist/katex-copytex.min.js"></script><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/katex-copytex@latest/dist/katex-copytex.min.css"><script>$(function () {
  $('span.katex-display').wrap('<div class="katex-wrap"></div>')
})</script><script>function addGitalkSource () {
  const ele = document.createElement('link')
  ele.rel = 'stylesheet'
  ele.href= 'https://cdn.jsdelivr.net/npm/gitalk/dist/gitalk.min.css'
  document.getElementsByTagName('head')[0].appendChild(ele)
}

function loadGitalk () {
  function initGitalk () {
    var gitalk = new Gitalk({
      clientID: 'e50742231659674c31e3',
      clientSecret: '59038139e289bc384e484d341205bbb95a123209',
      repo: 'TOMsworkspace.github.io',
      owner: 'TOMsworkspace',
      admin: ['TOMsworkspace'],
      id: '2c45f67e4010fcd16f926ae098a28fa6',
      language: '-zh-CN# en, zh-CN, zh-TW, es-ES, fr, ru',
      perPage: 10,
      distractionFreeMode: false,
      pagerDirection: 'last',
      createIssueManually: true,
      updateCountCallback: commentCount
    })
    gitalk.render('gitalk-container')
  }

  if (typeof Gitalk === 'function') initGitalk()
  else {
    addGitalkSource()
    $.getScript('https://cdn.jsdelivr.net/npm/gitalk@latest/dist/gitalk.min.js', initGitalk)
  }
}

function commentCount(n){
  let isCommentCount = document.querySelector('#post-meta .gitalk-comment-count')
  if (isCommentCount) {
    isCommentCount.innerHTML= n
  }
}

if ('Gitalk' === 'Gitalk' || !false) {
  if (false) btf.loadComment(document.getElementById('gitalk-container'), loadGitalk)
  else loadGitalk()
} else {
  function loadOtherComment () {
    loadGitalk()
  }
}</script><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><script id="click-show-text" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-show-text.min.js" async="async" mobile="false"></script><script>(function(){
  const bp = document.createElement('script');
  const curProtocol = window.location.protocol.split(':')[0];
  if (curProtocol === 'https'){
  bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
  }
  else{
  bp.src = 'http://push.zhanzhang.baidu.com/push.js';
  }
  bp.dataset.pjax = ''
  const s = document.getElementsByTagName("script")[0];
  s.parentNode.insertBefore(bp, s);
})()</script></div></body></html>